package jdbc;


import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class demo2 {

    public static void main(String[] args) {

        Connection connection=null;

        PreparedStatement statement=null;

        ResultSet resultSet=null;

        MysqlDataSource mysqlDataSource=new MysqlDataSource();




        mysqlDataSource.setURL( "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&allowPublicKeyRetrieval" + "=true&useSSL=false");

        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("Rsa181210");

        DataSource dataSource=mysqlDataSource;


        try{
            connection=dataSource.getConnection();

            statement=connection.prepareStatement("select * from exam_result where name=?");

            System.out.println("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            // 3. 用真实值替换占位符
            statement.setString(1, name);



            resultSet = statement.executeQuery();

            while(resultSet.next()){
                long id=resultSet.getLong(1);
                String name1=resultSet.getString(2);
                long chinese=resultSet.getLong(3);
                long math=resultSet.getLong(4);
                long english=resultSet.getLong(5);
                System.out.println("id="+id+"  name: "+name1+"  chinese="+chinese+"  math="+math+"  english="+english);

            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}

